package org.csu.gp_store.controller;

import org.csu.gp_store.common.CommonResponse;
import org.csu.gp_store.common.EmailCodeList;
import org.csu.gp_store.common.RandomCode;
import org.csu.gp_store.common.ResponseCode;
import org.csu.gp_store.entity.Account;
import org.csu.gp_store.entity.AccountAddress;
import org.csu.gp_store.service.AccountAddressService;
import org.csu.gp_store.service.AccountService;
import org.csu.gp_store.util.MD5Util;
import org.csu.gp_store.util.SentMailUtil;
import org.csu.gp_store.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;

import java.util.List;

import static org.csu.gp_store.common.EmailCodeList.BUYER_ACCOUNT_REGISTER;
import static org.csu.gp_store.common.EmailCodeList.addCode;

@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    AccountService accountService;

    @Autowired
    AccountAddressService accountAddressService;

    /**
     * 登录,登录成功返回token
     *
     * @param account 邮箱，密码
     * @param method  方法
     * @return CommonResponse token
     */
    @PostMapping("/login")
    public CommonResponse<String> login(@RequestBody Account account, @RequestParam String method) {
        String loginMethod = ("").equals(method) ? "EMAIL" : method;
        if (loginMethod.equals("EMAIL") && (null == account.getEmail() || null == account.getPassword())) {
            return CommonResponse.createForError("邮箱或密码不能为空");
        }

        String MD5PWD = MD5Util.getMD5String(account.getPassword());
        if (MD5PWD == null) {
            return CommonResponse.createForError("服务器异常,请重试");
        }
        String token = accountService.userLogin(account.getEmail(), MD5PWD, loginMethod);
        if (token != null) {
            return CommonResponse.createForSuccess(token, "登陆成功");
        }
        return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "账号或密码错误");
    }

    /**
     * 通过token获取账户信息
     *
     * @param MyToken token
     * @return 获取到的账户
     */
    @GetMapping("/info")
    public CommonResponse<Account> getCertainAccount(@RequestHeader("MyToken") String MyToken) {
        if (null == MyToken) {
            return CommonResponse.createForError("未登录，请登录后重试");
        }
        System.out.println("token:" + MyToken);
        String verifyToken = TokenUtil.getUserIdByToken(MyToken);
        if (verifyToken == null) {
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        Long accountID = Long.valueOf(verifyToken);
        Account account = accountService.getAccount(accountID);
        if (account == null) {
            return CommonResponse.createForError("校验错误，请重试");
        }
        return CommonResponse.createForSuccess(account);
    }

    /**
     * 经销商注册
     *
     * @param account 输入的账号信息
     * @return 是否注册成功, 或错误信息
     */
    @PostMapping("/register")
    public CommonResponse<String> register(@RequestBody Account account, @RequestParam("code") String verifyCode) {
        // 空判断
        if (null == verifyCode || "".equals(verifyCode)) {
            return CommonResponse.createForError("验证码不能为空");
        }
        // 先验证验证码是否正确
        String trueCode = EmailCodeList.getCode(account.getEmail(), BUYER_ACCOUNT_REGISTER);
        // 验证码过期 或者根本没发给经销商验证码
        if (null == trueCode) {
            return CommonResponse.createForError("请重试发送验证码");
        }
        System.out.println("verifyCode:" + verifyCode);
        System.out.println("trueCode" + trueCode);
        // 判断验证码是否正确
        if (!trueCode.equals(verifyCode)) {
            return CommonResponse.createForError("验证码错误，请重新输入！");
        }

        // 判断邮箱,商家名是否存在
        if (accountService.emailExist(account.getEmail())) {
            return CommonResponse.createForError("邮箱" + account.getEmail() + "已存在");
        }
        if (accountService.nameExist(account.getName())) {
            return CommonResponse.createForError("商家名" + account.getName() + "已存在");
        }
        account.setPassword(MD5Util.getMD5String(account.getPassword()));
        if (accountService.createNewUser(account) == 1) {
            return CommonResponse.createForSuccessMsg("注册成功");
        }
        return CommonResponse.createForError("服务器错误，创建账号异常，请重试");
    }

    /**
     * 经销商修改信息 包含密码 不填写默认为不修改
     *
     * @param MyToken token
     * @param account 修改后的账户信息
     * @return 修改是否成功
     */
    @PostMapping("/info")
    public CommonResponse<Account> alterInfo(@RequestBody Account account,
                                             @RequestHeader("MyToken") String MyToken) {
        if (("").equals(MyToken)) {
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        String verifyToken = TokenUtil.getUserIdByToken(MyToken);
        if (verifyToken == null) {
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        Long accountID = Long.valueOf(verifyToken);
        Account modifiedAccount = accountService.getAccount(accountID);
        modifiedAccount.setEmail(account.getEmail() != null ? account.getEmail() : modifiedAccount.getEmail());
        modifiedAccount.setAddress(account.getAddress() != null ? account.getAddress() : modifiedAccount.getAddress());
        modifiedAccount.setDescription(account.getDescription() != null ? account.getDescription() : modifiedAccount.getDescription());
        modifiedAccount.setName(account.getName() != null ? account.getName() : modifiedAccount.getName());
        modifiedAccount.setPassword(account.getPassword() != null ? MD5Util.getMD5String(account.getPassword()) : modifiedAccount.getPassword());
        if (accountService.modifyInfo(modifiedAccount) == 1) {
            return CommonResponse.createForSuccess(modifiedAccount, "修改成功");
        }
        return CommonResponse.createForError("修改失败");
    }

    /**
     * 获取所有账户，不知道有什么用
     *
     * @return IPage
     */
    //    @GetMapping
    //    public CommonResponse<IPage> getAllAccounts() {
    //        IPage pages = accountService.getAccountList();
    //        return CommonResponse.createForSuccess(pages);
    //    }

    /**
     * 注销
     *
     * @param account 传入的密码和邮箱
     * @param MyToken token校验
     * @return 是否成功
     */
    @PostMapping("/cancel")
    public CommonResponse<String> readyCancelAccount(@RequestBody Account account,
                                                     @RequestHeader("MyToken") String MyToken) {
        if (("").equals(MyToken)) {
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        String verifyToken = TokenUtil.getUserIdByToken(MyToken);
        if(verifyToken == null){
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        Long accountID = Long.valueOf(verifyToken);
        Account account1 = accountService.getAccount(accountID);
        if (account != null) {
            if (account1.getPassword().equals(MD5Util.getMD5String(account.getPassword()))) {
                if (accountService.cancelAccount(accountID, account.getPassword(), account.getEmail()) != 1) {
                    return CommonResponse.createForError("账号错误，请重新登录");
                }
                return CommonResponse.createForSuccessMsg("注销流程已开始");
            } else {
                return CommonResponse.createForError("密码不正确，请重新确认");
            }
        } else {
            return CommonResponse.createForError("账号不存在");
        }
    }

    /**
     * 注销确认
     *
     * @param verifyCode 邮箱发的验证码
     * @param myToken    token校验
     * @return 返回是否成功
     */
    @PostMapping("/cancel/submit")
    public CommonResponse<String> submitCancelAccount(@RequestParam String verifyCode,
                                                      @RequestHeader("MyToken") String myToken) {
        // 空判断
        if (null == verifyCode || "".equals(verifyCode)) {
            return CommonResponse.createForError("验证码不能为空");
        }
        // MyToken判断
        if(myToken == null || ("").equals(myToken)){
            return CommonResponse.createForError("请登录后再进行该操作");
        }
        String verifyToken = TokenUtil.getUserIdByToken(myToken);
        if(verifyToken == null){
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        Long accountID = Long.valueOf(verifyToken);
        Account account = accountService.getAccount(accountID);
        if (account == null) {
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }

        String trueCode = EmailCodeList.getCode(account.getEmail(), EmailCodeList.BUYER_ACCOUNT_CANCEL);
        // 验证码过期 或者根本没发给经销商验证码
        if (null == trueCode) {
            return CommonResponse.createForError("请重试发送验证码");
        }

        // 判断验证码是否正确
        if (!trueCode.equals(verifyCode)) {
            return CommonResponse.createForError("验证码错误，请重新输入！");
        }
        // TODO 注销的Service调用
        if (accountService.cancelSubmit(accountID) == 1) {
            return CommonResponse.createForSuccessMsg("您已注销成功，欢迎再次使用好搭档微商城!");
        }
        return CommonResponse.createForError("账号出现错误，请稍后重试");
    }

    /**
     * @param email 收验证码的邮箱
     * @return 是否返回成功
     * @author huangzhangyan
     */
    @PostMapping("/cancel/verifyCode")
    public CommonResponse<String> sendVerifyCodeForCancel(@RequestParam("email") String email) {
        System.out.println("email: " + email);
        Account account = accountService.getAccountByEmail(email);
        if (account != null) {
            String verifyCode = RandomCode.getRandomCode();
            String msg = "您的验证码为:" + verifyCode + "，如果您未进行过这样的操作请无视该信息。";
            try {
                new SentMailUtil().sentSimpleMail("好搭档微商城-经销商注销验证码", msg, account.getEmail());
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return CommonResponse.createForSuccessMsg("验证码已发送至您的邮箱");
        }
        return CommonResponse.createForError("未找到账号，请重试");
    }

    @PostMapping("/register/verifyCode")
    public CommonResponse<String> sendVerifyCodeForRegister(@RequestParam("email") String email) {
        System.out.println("email: " + email);
        if (accountService.emailExist(email)) {
            return CommonResponse.createForError("邮箱已被注册，请更换后重试");
        }
        String verifyCode = RandomCode.getRandomCode();
        String msg = "您的验证码为:" + verifyCode + "，如果您未进行过这样的操作请无视该信息。";
        try {
            new SentMailUtil().sentSimpleMail("好搭档微商城-经销商注册验证码", msg, email);
            addCode(email, verifyCode, BUYER_ACCOUNT_REGISTER);
        } catch (MessagingException e) {
            e.printStackTrace();
            return CommonResponse.createForSuccessMsg("验证码发送失败");
        }
        return CommonResponse.createForSuccessMsg("验证码已发送至您的邮箱");
    }
     //添加新地址
    @PostMapping("/address/new")
    public CommonResponse<String> addNewAddress(@RequestBody AccountAddress accountAddress,
                                                @RequestHeader("MyToken") String MyToken){
        if(accountAddress.getAddress()==null||accountAddress.getPhone()==null||accountAddress.getName()==null){
            return CommonResponse.createForError("请填写完整信息");
        }
        if(MyToken == null || ("").equals(MyToken)){
            return CommonResponse.createForError("请登录后再进行该操作");
        }
        String verifyToken = TokenUtil.getUserIdByToken(MyToken);
        if(verifyToken==null){
            return CommonResponse.createForError("身份校验失败，请重新登陆");
        }
        Long AccountID = Long.valueOf(verifyToken);
        accountAddress.setAccountID(AccountID);
        if(accountAddressService.insertAccountAddress(accountAddress)!=0){
            return CommonResponse.createForSuccessMsg("添加成功");
        }
        return CommonResponse.createForError("该地址已存在，请重新填写");
    }
    //获取用户的所有地址表
    @GetMapping("/address")
    public CommonResponse<List<AccountAddress>> getAllAddress(@RequestHeader("MyToken") String MyToken){
        if(MyToken == null || ("").equals(MyToken)){
            return CommonResponse.createForError("请登录后再进行该操作");
        }
        String verifyToken = TokenUtil.getUserIdByToken(MyToken);
        if(verifyToken==null){
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        Long accountID = Long.valueOf(verifyToken);
        return CommonResponse.createForSuccess(accountAddressService.getAddressByAccountID(accountID));
    }
    //获取单个地址
    @GetMapping("/address/{indexID}")
    public CommonResponse<AccountAddress> getCertainAddress(@RequestHeader("MyToken") String MyToken,
                                                            @PathVariable("indexID") Long indexID){
        if(MyToken == null || ("").equals(MyToken)){
            return CommonResponse.createForError("请登录后再进行该操作");
        }
        String verifyToken = TokenUtil.getUserIdByToken(MyToken);
        if(verifyToken==null){
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        Long accountID = Long.valueOf(verifyToken);
        return CommonResponse.createForSuccess(accountAddressService.getAddressByID(indexID));
    }
    //修改地址
    @PostMapping("/address/{indexID}")
    public CommonResponse<String> alterCertainAddress(@PathVariable("indexID") Long indexID,
                                                      @RequestHeader("MyToken") String MyToken,
                                                      @RequestBody AccountAddress accountAddress){
        if(MyToken == null || ("").equals(MyToken)){
            return CommonResponse.createForError("请登录后再进行该操作");
        }
        String verifyToken = TokenUtil.getUserIdByToken(MyToken);
        if(verifyToken==null){
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        Long accountID = Long.valueOf(verifyToken);
        if(accountAddress.getAddress()!=null){
            if(accountAddressService.updateAddress(indexID,accountAddress.getAddress())==0)
                return CommonResponse.createForError("修改失败，未找到需要修改的条目");
        }
        if(accountAddress.getName()!=null){
            if(accountAddressService.updateName(indexID,accountAddress.getName())==0)
                return CommonResponse.createForError("修改失败，未找到需要修改的条目");
        }
        if(accountAddress.getPhone()!=null){
            if(accountAddressService.updatePhone(indexID,accountAddress.getPhone())==0)
                return CommonResponse.createForError("修改失败，未找到需要修改的条目");
        }
        return CommonResponse.createForSuccessMsg("修改成功");
    }
    //删除单个地址
    @PostMapping("/address/delete")
    public CommonResponse<String> deleteCertainAddress(@RequestParam("indexID") Long indexID,
                                                       @RequestHeader("MyToken") String MyToken){
        if(MyToken == null || ("").equals(MyToken)){
            return CommonResponse.createForError("请登录后再进行该操作");
        }
        String verifyToken = TokenUtil.getUserIdByToken(MyToken);
        if(verifyToken==null){
            return CommonResponse.createForError("身份校验失败，请重新登录");
        }
        if(accountAddressService.deleteAccountAddress(indexID)==0){
            return CommonResponse.createForError("删除失败，请稍后重试");
        }
        return CommonResponse.createForSuccessMsg("删除完成");
    }
}
